package com.xiyi.shouxin.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

public class JdbcStatementCreator implements PreparedStatementCreator {
    private String sql;
    private List<Object> args;
    private List<Integer> types;

    public JdbcStatementCreator(final String sql, final List<Object> args, List<Integer> types) {
        this.sql = sql;
        this.args = args;
        this.types = types;
    }

    @Override
    public @NonNull PreparedStatement createPreparedStatement(@NonNull Connection con) throws SQLException {
        if (!StringUtils.hasText(sql) || args.size() == 0 || args.size() != types.size()) {
            throw new SQLException("预执行SQL异常");
        }
        PreparedStatement pstmt = con.prepareStatement(this.sql,PreparedStatement.RETURN_GENERATED_KEYS);
        if (pstmt == null) {
            throw new SQLException("预执行SQL异常");
        }
        for (int i = 0; i < args.size(); i++) {
            pstmt.setObject(i + 1, args.get(i), types.get(i));
        }
        return pstmt;
    }

}
